﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Configuration;

namespace ElectronicJournal.Admin
{
    /// <summary>
    /// Summary description for Handler
    /// </summary>
    public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string imagePath = context.Request.QueryString["id"];

            MemoryStream memoryStream = new MemoryStream();
            byte[] topBanner = getBannerFromDb("верх");
            memoryStream.Write(topBanner, 0, topBanner.Length);
            context.Response.Buffer = true;
            context.Response.BinaryWrite(topBanner);
            memoryStream.Dispose();


            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private byte[] getBannerFromDb(string position)
        {
            byte[] res = new byte[8000];
            try
            {

                int fileID;
                SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
                cnn.Open();
                SqlDataAdapter da = new SqlDataAdapter("select banner.conten from  banner where position=@pos", cnn);
                da.SelectCommand.Parameters.AddWithValue("@pos", position);
                //SqlCommand cmd = new SqlCommand();

                //cmd.Connection = cnn;

                //cmd.CommandText = "select banner.content from  banner where position=@pos";

                //cmd.CommandType = CommandType.Text;

                //cmd.Parameters.Add("@pos", SqlDbType.NChar);
                //cmd.Parameters["@pos"].Value = position;


                //SqlDataAdapter da = new SqlDataAdapter();

                //da.SelectCommand = cmd;

                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    res = (byte[])dt.Rows[0][0];
                }

            }
            catch
            {
            }
            return res;

        }

        private static string GetTempFolderName()
        {
            string strTempFolderName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\";

            if (Directory.Exists(strTempFolderName))
            {
                return strTempFolderName;
            }
            else
            {
                Directory.CreateDirectory(strTempFolderName);
                return strTempFolderName;
            }
        }
    }
}